package shuashuami.hb.com.avtivity.agent;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.avtivity.AbActivity;
import shuashuami.hb.com.entity.agent.User;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.glid.GlidUtil;
import shuashuami.hb.com.http.ChangeAUserImageMessageHttp;
import shuashuami.hb.com.http.HttpAgentMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.listener.IDialogBtnClickListener;
import shuashuami.hb.com.manager.agent.UserManager;
import shuashuami.hb.com.util.DialogUtils;
import shuashuami.hb.com.util.FileStorage;
import shuashuami.hb.com.view.IOSAlertDialog;
import shuashuami.hb.com.view.MyDialog;

/**
 * <b>类   名：</b>${TYPE_NAME} <br/>
 * <b>类描述：</b> <br/>
 * <b>创建人：</b>zhangqi<br/>
 * <b>创建时间：</b>2017/6/15<br/>
 * <b>修改人：</b>zhangqi<br/>
 * <b>修改时间：</b>2017/6/15<br/>
 * <b>修改备注：</b><br/>
 *
 * @version 1.0.0<br/>
 */
public class UserInfoAct extends AbActivity implements PermissionListener {

    GlidUtil glidUtil;

    String[][] infos = {
            {"头像", "1", "", "1"},
            {"ID", "", "25654", ""},
            {"用户名", "", "飞翔的企鹅", ""},
            {"姓名", "", "张小凡", "1"},
            {"身份证号", "", "1234567890", "1"},
            {"QQ", "", "54321", "1"},
            {"邮箱", "", "54321@qq.com", "1"},
            {"手机号", "", "15254321", ""}
    };

    String[] values = {"", "", "", "realname", "identify", "qq", "email", "mobile"};

    LayoutInflater inflater;
    LinearLayout userinfo_content;

    private ImageView imageIcon;

    @Override
    protected void initUI() {
        setAbContentView(R.layout.act_auserinfo);
        setTitleBar("个人信息");
        glidUtil = new GlidUtil(this);
        userinfo_content = (LinearLayout) findViewById(R.id.userinfo_content);

    }

    @Override
    protected void initData() {
        inflater = LayoutInflater.from(this);
        setUserInfo();


        for (int i = 0; i < infos.length; i++) {
            // 第一个
            View view = inflater.inflate(R.layout.ui_item_userinfo, null);
            view.setTag(i);
            ViewGroup v = (ViewGroup) view.findViewById(R.id.lin_item_userinfo);
            TextView space = (TextView) view.findViewById(R.id.userinfo_space);
            TextView textTitle = (TextView) v.getChildAt(0);
            textTitle.setText(infos[i][0]);

            // 第二个
            imageIcon = (ImageView) v.getChildAt(1);
            if (infos[i][1] != null && infos[i][1].equals("1")) {
                imageIcon.setVisibility(View.VISIBLE);
            }

            if (i == 0 && infos[0][2] != null && !infos[0][2].equals("")) {
                glidUtil.uploadCircle(infos[0][2], imageIcon, R.mipmap.ssm_icon_11);
            }
            // 第三个
            TextView textValue = (TextView) v.getChildAt(2);
            if (i == 0 || infos[i][2] == null || infos[i][2].equals("")) {
                textValue.setVisibility(View.GONE);
            } else {
                textValue.setText(infos[i][2]);
            }

            // 第四个
            ImageView imageNext = (ImageView) v.getChildAt(3);
            if (infos[i][3] == null || infos[i][3].equals("")) {
                imageNext.setVisibility(View.GONE);
            }

            if (i == 1) {
                space.setVisibility(View.VISIBLE);
            }
            userinfo_content.addView(view);
        }

    }

    public void setUserInfo() {
        // 初始化头像
        User user = UserManager.getInstance().getUser();
        infos[0][2] = user.getAvatar();
        infos[1][2] = user.getId();
        infos[2][2] = user.getUsername();
        infos[3][2] = user.getRealname();
        infos[4][2] = user.getIdentify();
        infos[5][2] = user.getQq();
        infos[6][2] = user.getEmail();
        infos[7][2] = user.getMobile();
    }

    @Override
    protected void initListener() {

    }


    public void sendUpdateMessage(final int type, final Bundle value) {

        String key = values[type];


        HttpOnNextListener<String> httpOnNextListener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(final String s) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        resloveChangeMsg(s, type, value);

                    }
                });

            }
        };


        HttpAgentMethods.changeMessage(httpOnNextListener,
                UserManager.getInstance().getUser().getId(),
                key,
                value.getString("0")
        );

    }


    public void resloveChangeMsg(String str, int type, Bundle value) {
        try {
            JSONObject object = new JSONObject(str);
            int status = object.getInt("status");
            if (status == 203) {
                LoginHttp loginHttp = new LoginHttp(UserInfoAct.this);
                loginHttp.login();
                return;
            }
            if (status == 200) {
                String message = object.getString("message");
                String content = object.getString("content");
                Toast.makeText(UserInfoAct.this, message, Toast.LENGTH_LONG).show();
                refershUI(type, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(UserInfoAct.this, "json解析异常", Toast.LENGTH_LONG).show();
        }


    }

    public void refershUI(final int type, final Bundle value) {
        if (type == 3) {
            UserManager.getInstance().getUser().setRealname(value.getString("0"));

        }

        infos[type][2] = value.getString("0");

        ViewGroup gourp = (ViewGroup) userinfo_content.getChildAt(type + 1);

        gourp = (ViewGroup) gourp.findViewById(R.id.lin_item_userinfo);

        TextView textValue = (TextView) gourp.getChildAt(2);

        textValue.setText(infos[type][2]);

    }

    public void onItemChange(View view) {

        final int tag = Integer.parseInt(view.getTag().toString());
        if (tag == 0) {
            imgPhone();
        } else {
            if (infos[tag][3].equals("")) return;

            DialogUtils utils = new DialogUtils(this, DialogUtils.DialogStyle.EditDialog);


            utils.setMyTitle(infos[tag][0]);


            utils.registerBtnClick(new IDialogBtnClickListener() {
                @Override
                public void onLeftBtnClick() {

                }

                @Override
                public void onRightBtnClick(Bundle value) {
                    sendUpdateMessage(tag, value);
                }
            });

            utils.show();
        }
    }

    private Uri imageUri;// 原图保存地址
    private boolean isClickCamera = false;// 是否拍照
    private String imagePath;

    private List<File> list = new ArrayList<>();
    private List<String> filePath;
    private File iconPath = null;
    private File cropPath = null;
    private static final int REQUEST_PICK_IMAGE = 101; // 相册选取
    private static final int REQUEST_CAPTURE = 102; // 拍照
    private static final int REQUEST_PICTURE_CUT = 103; // 剪裁图片
    private static final int REQUEST_CODE_SETTING = 300;

    private static final int REQUEST_CODE_PERMISSION_SD = 100;
    private static final int REQUEST_CODE_PERMISSION_OTHER = 101;

    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    MyDialog dialog;

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void imgPhone() {
        dialog = new MyDialog(this);
        // TODO Auto-generated method stub
        TextView tv1 = dialog.getTakePhone();
        TextView tv2 = dialog.getSystemphone();
        tv1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    AndPermission.with(UserInfoAct.this)
                            .requestCode(REQUEST_CODE_PERMISSION_SD)
                            .permission(PERMISSIONS)
                            .rationale(new RationaleListener() {

                                @Override
                                public void showRequestPermissionRationale(
                                        int requestCode, Rationale rationale) {
                                    // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                    AndPermission.rationaleDialog(
                                            UserInfoAct.this, rationale)
                                            .show();
                                }
                            }).send();
                } else {
                    openCamera();
                }
                isClickCamera = true;
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    AndPermission.with(UserInfoAct.this)
                            .requestCode(REQUEST_CODE_PERMISSION_OTHER)
                            .permission(PERMISSIONS)
                            .rationale(new RationaleListener() {

                                @Override
                                public void showRequestPermissionRationale(
                                        int requestCode, Rationale rationale) {
                                    // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                    AndPermission.rationaleDialog(
                                            UserInfoAct.this, rationale)
                                            .show();
                                }
                            }).send();
                } else {
                    // Toast.makeText(FeedbackActivity.this,
                    // "FeedbackActivity", Toast.LENGTH_SHORT).show();
                    selectFromAlbum();
                }
                isClickCamera = false;
            }
        });
        dialog.show();
    }

    /**
     * 打开系统相机(这个方法已经适配android7.0中的私有目录被限制访问权限)
     * 从Android7.0开始在应用间共享文件时已经不允许使用intent来传递file://URI类型的uri了
     * 只允许传递content://URI类型的uri
     */
    private void openCamera() {
        File file = new FileStorage().createIconFile();
        iconPath = file;
        // 判断当前的SDK版本是否在7.0及以上
        // 是的话就使用最新的文件传递机制，否则就使用老的文件传递机制
        if (Build.VERSION.SDK_INT >= 24) {
            // 通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(UserInfoAct.this,
                    "shuashuami.hb.com.hbclient.fileprovider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 24) {
            // 添加这一句表示对目标应用临时授权该Uri所代表的文件(授予 URI 临时访问权限)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);// 设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 将拍取的照片保存到指定URI
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        AndPermission.onRequestPermissionsResult(requestCode, permissions,
                grantResults, this);
    }

    @Override
    public void onFailed(int arg0, List<String> arg1) {
        // TODO Auto-generated method stub
        switch (arg0) {
            case REQUEST_CODE_PERMISSION_SD: {
                // Toast.makeText(this, "请打开必要权限", Toast.LENGTH_SHORT).show();
                showTipsDialog();
                break;
            }
            case REQUEST_CODE_PERMISSION_OTHER: {
                // Toast.makeText(this, "请打开必要权限", Toast.LENGTH_SHORT).show();
                showTipsDialog();
                break;
            }
        }
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, arg1)) {
        }
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        IOSAlertDialog dialog = new IOSAlertDialog(this);
        dialog.builder().setTitle("提示")
                .setMessage("当前应用缺少相机权限。\n请到\"设置\"-\"权限\"-打开所需权限。")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }

                }).show();
    }

    @Override
    public void onSucceed(int arg0, List<String> arg1) {
        // TODO Auto-generated method stub
        switch (arg0) {
            case REQUEST_CODE_PERMISSION_SD:
                openCamera();
                break;
            case REQUEST_CODE_PERMISSION_OTHER:
                selectFromAlbum();
                break;
        }
    }

    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        try {
            imageUri = data.getData();
            if (DocumentsContract.isDocumentUri(this, imageUri)) {
                // 如果是document类型的uri,则通过document id处理
                String docId = DocumentsContract.getDocumentId(imageUri);
                if ("com.android.providers.media.documents".equals(imageUri
                        .getAuthority())) {
                    String id = docId.split(":")[1];// 解析出数字格式的id
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            selection);
                } else if ("com.android.downloads.documents".equals(imageUri
                        .getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
                // 如果是content类型的Uri，则使用普通方式处理
                imagePath = getImagePath(imageUri, null);
            } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
                // 如果是file类型的Uri,直接获取图片路径即可
                imagePath = imageUri.getPath();
            }
            cropPhoto();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private void handleImageBeforeKitKat(Intent intent) {
        imageUri = intent.getData();
        imagePath = getImagePath(imageUri, null);
        cropPhoto();
    }

    /**
     * 裁剪
     */
    private void cropPhoto() {
        File file = new FileStorage().createCropFile();
        cropPath = file;
        Uri outputUri = Uri.fromFile(file);// 缩略图保存地址
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUEST_PICTURE_CUT);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null,
                null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void upload(File file) {
        List<String> images = new ArrayList<>();
        images.add(file.getAbsolutePath());
        ChangeAUserImageMessageHttp changeCUserImageMessageHttp = new ChangeAUserImageMessageHttp(this, imageIcon);
        changeCUserImageMessageHttp.uploadImg(images);
    }


    private void addPhoto(String imgPath, Uri imgUri) {
        list.clear();

        if (imgUri != null) {
            glidUtil.uploadCircle(iconPath.getAbsolutePath(), imageIcon, R.mipmap.ssm_icon_11);
            upload(iconPath);
        } else {
            glidUtil.uploadCircle(cropPath.getAbsolutePath(), imageIcon, R.mipmap.ssm_icon_11);
            upload(cropPath);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_PICK_IMAGE:// 从相册选择
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat(data);
                } else {
                    handleImageBeforeKitKat(data);
                }
                break;
            case REQUEST_CAPTURE:// 拍照
                addPhoto("", imageUri);
                break;
            case REQUEST_PICTURE_CUT:// 裁剪完成
                try {
                    addPhoto(imagePath, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_CODE_SETTING:
                Toast.makeText(this, "从设置返回", Toast.LENGTH_LONG).show();
                break;
        }

    }
}
